package com.ITArmy.util;

import com.ITArmy.common.ServerResponse;
import com.google.gson.Gson;
import com.mysql.cj.util.Base64Decoder;
import com.qiniu.common.Region;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class pictureChange {
    //base64字符串转化成图片
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region0());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //...生成上传凭证，然后准备上传
    String accessKey = "nuhgqcLNFz5MgHnT45MZBiiLdhtQsTL2xodwkCbE";
    String secretKey = "nqRXdraD468LQLkHCWspjgZYSsC7dVNo-H6fQRyL";
    String bucket = "itarmy";
    //如果是Windows情况下，格式是 D:\\qiniu\\test.png
    String localFilePath = "/home/qiniu/test.png";
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    String key = null;

    public ServerResponse uploadHeader(@RequestParam String base64Data, HttpServletRequest request, String picturePath) {
        ServerResponse serverResponse;
        String tempFileName;
        String basePath = request.getSession().getServletContext().getRealPath(picturePath);
        System.out.println("路径为：" + basePath);
        String basePath2 = request.getRealPath("/");  //获取项目根目录绝对路径(xxx/Rainbow/)
        System.out.println("路径2为：" + basePath2);
        try {
            String dataPrix = "";
            String data = "";
            if (base64Data == null || "".equals(base64Data)) {
                throw new Exception("上传失败，上传图片数据为空");
            } else {
                String[] d = base64Data.split("base64,");
                if (d != null && d.length == 2) {
                    dataPrix = d[0];
                    data = d[1];
                } else {
                    throw new Exception("上传失败，数据不合法");
                }
            }
            String suffix = "";
            if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//编码的jpeg图片数据
                suffix = ".jpg";
            } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//编码的icon图片数据
                suffix = ".ico";
            } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//编码的gif图片数据
                suffix = ".gif";
            } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//编码的png图片数据
                suffix = ".png";
            } else {
                throw new Exception("上传图片格式不合法");
            }
//重命名文件名称
            tempFileName = String.valueOf(Calendar.getInstance().getTimeInMillis()) + suffix;
            String uuid = UUID.randomUUID().toString().replace("-", "");
            tempFileName = uuid + tempFileName;
            System.out.println("重命名文件名称" + tempFileName);
            
            Base64Decoder decoder = new Base64Decoder();
            byte[] bs = Base64Decoder.decode(data.getBytes(), 0, data.length()); //将base64转换成字节流decoder.decode
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bs);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                String finalUrl = "http://pz7sjost8.bkt.clouddn.com/" + putRet.hash;
                return ServerResponse.createBySuccess("上传成功", finalUrl);
            } catch (Exception e) {
                return ServerResponse.createByErrorMesage("上传失败");
            }

        } catch (Exception e) {
            return ServerResponse.createByError();
        }

    }


}
